<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('customCode:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="目标表单名称">
                <a-input v-model.trim="queryParam.tableReName" allow-clear placeholder="请输入目标表单名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="自定义编码">
                <a-input v-model.trim="queryParam.encode" allow-clear placeholder="请输入自定义编码"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" >
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" >查询</a-button>
                <a-button style="margin-left: 8px" @click="Reset">重置</a-button>
                <!--                <a @click="toggleAdvanced" style="margin-left: 8px">-->
                <!--                  {{ advanced ? '收起' : '展开' }}-->
                <!--                  <a-icon :type="advanced ? 'up' : 'down'"/>-->
                <!--                </a>-->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :rowKey="(record) => record.id"
      >
        <template class="table-operator" slot="operator" v-if="hasPerm('customCode:add')">
          <a-button type="primary" v-if="hasPerm('customCode:add')" icon="plus" @click="$refs.addForm.add()">
            新增自定义编号规则
          </a-button>
          <!--          <a-button type="danger" :disabled="selectedRowKeys.length < 1" v-if="hasPerm('customCode:delete')" @click="batchDelete"><a-icon type="delete"/>批量删除</a-button>-->
          <!--          <x-down-->
          <!--            v-if="hasPerm('customCode:export')"-->
          <!--            ref="batchExport"-->
          <!--            @batchExport="batchExport"-->
          <!--          />-->
        </template>
        <span slot="timeFormatScopedSlots" slot-scope="text, record">
          {{ 'timeFormat' | dataSource(text, record) }}
        </span>
        <span slot="formatScopedSlots" slot-scope="record">
          <a-tag color="blue">{{ getFormat(record) }}</a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <a v-if="hasPerm('customCode:edit')" @click="$refs.editForm.edit(record)">编辑</a>
          <!--          <a-divider type="vertical" v-if="hasPerm('customCode:edit') & hasPerm('customCode:delete')"/>-->
          <!--          <a-popconfirm v-if="hasPerm('customCode:delete')" placement="topRight" title="确认删除？" @confirm="() => singleDelete(record)">-->
          <!--            <a>删除</a>-->
          <!--          </a-popconfirm>-->
        </span>
      </s-table>
      <add-form ref="addForm" @ok="handleOk"/>
      <edit-form ref="editForm" @ok="handleOk"/>
    </a-card>
  </div>
</template>
<script>
import { STable, XDown } from '@/components'
import { customCodePage, customCodeDelete, customCodeExport } from '@/api/modular/main/customcode/customCodeManage'
import addForm from './addForm.vue'
import editForm from './editForm.vue'
import timeFormatData from '@/api/modular/main/customcode/customCodeEnum'

export default {
  components: {
    STable,
    addForm,
    editForm,
    XDown
  },
  filters: {
    dataSource: function (name, code) {
      return timeFormatData[code].name
    }
  },
  data() {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '序号',
          align: 'center',
          dataIndex: 'index',
          key: 'index',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '目标表单名称',
          align: 'center',
          dataIndex: 'tableReName'
          // scopedSlots: { customRender: 'tableNameScopedSlots' }
        },
        {
          title: '自定义编码',
          align: 'center',
          dataIndex: 'encode'
        },
        {
          title: '时间选项',
          align: 'center',
          dataIndex: 'timeFormat',
          scopedSlots: { customRender: 'timeFormatScopedSlots' }
        },
        {
          title: '流水号位数',
          align: 'center',
          dataIndex: 'serialNum'
        },
        {
          title: '自由字段',
          align: 'center',
          dataIndex: 'freeField'
        },
        {
          title: '规则示例',
          align: 'center',
          dataIndex: '',
          scopedSlots: { customRender: 'formatScopedSlots' }
        }
      ],
      tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return customCodePage(Object.assign(parameter, this.queryParam)).then((res) => {
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      }
    }
  },
  created() {
      if (this.hasPerm('customCode:edit') || this.hasPerm('customCode:delete')) {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      })
    }
  },
  methods: {
    /**
     * 重置
     */
    Reset() {
      this.queryParam = {}
      this.$refs.table.refresh(true)
    },
    /**
     * 单个删除
     */
    singleDelete(record) {
      const param = [{ 'id': record.id }]
      this.customCodeDelete(param)
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { 'id': d }
      })
      this.customCodeDelete(paramIds)
    },
    customCodeDelete(record) {
      customCodeDelete(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.clearRefreshSelected()
        } else {
          this.$message.error('删除失败') // + res.message
        }
      })
    },
    /**
     * 批量导出
     */
    batchExport() {
      const paramIds = this.selectedRowKeys.map((d) => {
        return { 'id': d }
      })
      customCodeExport(paramIds).then((res) => {
        this.$refs.batchExport.downloadfile(res)
      })
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getFormat(record) {
      // 获取当前时间
      let time = ''
      if (record.timeFormat >= 0) {
        time = new Date().getFullYear()
      }
      if (record.timeFormat >= 1) {
        time = time + '' + (new Date().getMonth() + 1)
      }
      if (record.timeFormat === 2) {
        time = time + '' + new Date().getDate()
      }
      if (record.timeFormat === 3) {
        time = ''
      }
      // 获取最小位数
      let numberFirst = ''
      for (let i = 0; i < record.serialNum; i++) {
        if (i !== record.serialNum - 1) {
          numberFirst = numberFirst + '0'
        } else {
          numberFirst = numberFirst + '1'
        }
      }
      // 获取最大位数
      let numberLast = ''
      for (let i = 0; i < record.serialNum; i++) {
        numberLast = numberLast + '9'
      }
      const format = record.encode + time
      return format + numberFirst + record.freeField + '~' + format + numberLast + record.freeField
    }
  }
}
</script>
<style lang = "less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
